package com.xuecheng.manage_media.service;

import com.xuecheng.framework.domain.media.MediaFile;
import com.xuecheng.framework.domain.media.request.QueryMediaFileRequest;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_media.dao.MediaFileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 媒资文件服务接口
 */
@Service
public class MediaFileService {

    @Autowired
    private MediaFileRepository mediaFileRepository;

    /**
     * 分页条件查询
     * 查询mongoDB数据库获取媒资文件信息
     * @param page
     * @param size
     * @param queryMediaFileRequest
     * @return
     */
    public QueryResponseResult findList(int page, int size, QueryMediaFileRequest queryMediaFileRequest) {
        if (queryMediaFileRequest == null) {
            queryMediaFileRequest = new QueryMediaFileRequest();
        }

        //1. 定义存放条件值对象
        MediaFile mediaFile = new MediaFile();
            //设置前端传过来的文件原始名, 用于搜索
        String fileOriginalName = queryMediaFileRequest.getFileOriginalName();
        if (!StringUtils.isEmpty(fileOriginalName)) {
            mediaFile.setFileOriginalName(fileOriginalName);
        }
            //设置前端传过来的文件tag标签, 用于搜索
        String tag = queryMediaFileRequest.getTag();
        if (!StringUtils.isEmpty(tag)) {
            mediaFile.setTag(tag);
        }
            //设置文件处理状态
        String processStatus = queryMediaFileRequest.getProcessStatus();
        if (!StringUtils.isEmpty(processStatus)) {
            mediaFile.setProcessStatus(processStatus);
        }
        // 2.条件匹配器
            // tag字段和fileOriginalName字段模糊匹配 , 不设置代表默认匹配
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("tag",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("fileOriginalName", ExampleMatcher.GenericPropertyMatchers.contains());
        // 3. 定义Example实例
        Example<MediaFile> example = Example.of(mediaFile, exampleMatcher);
        // 4. 设置分页
        if (page <= 0 ) {
            page = 1;
        }
        if (size <= 0) {
            size = 10;
        }
            // "0" 代表第一页
        Pageable pageable = new PageRequest(page - 1, size);
        // 5. 查询结果
        Page<MediaFile> mediaFiles = mediaFileRepository.findAll(example, pageable);

        // 6. 响应
        QueryResult<MediaFile> queryResult = new QueryResult<>();
        queryResult.setTotal(mediaFiles.getTotalElements());
        queryResult.setList(mediaFiles.getContent());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }
}
